﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.Tasks;
using ESRI.ArcGIS.Client.Local;
using System.ComponentModel;
using System.Collections;
using System.Data;


namespace AtlasGis
{
    /// <summary>
    /// Interaction logic for ucBD_hanhchinh.xaml
    /// </summary>
    public partial class ucBD_hanhchinh : UserControl, INotifyPropertyChanged
    {
        private string tkdsDisplay = "Dân số";
        private string tkdtDisplay = "Diện tích (nghìn m^2)";
        private string[] strTenBD;
        private Int64[] strDS;
        private double[] strDT;
        private long ds;
        private double dt;
        private string ten;
        private int slTK;
        public ucBD_hanhchinh()
        {
            InitializeComponent();
               LocalMapService.GetServiceAsync(@"..\..\maps\mpks\VN_hanhchinh.mpk", (localMapService) =>
            {
                _mapService = localMapService;
                MyMap.IsEnabled = true;
                DataContext = this;
                IsBusy = false;
            });

               khoitaoTK();
            
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private bool _isBusy = true;
        public bool IsBusy
        {
            get
            {
                return _isBusy;
            }
            set
            {
                _isBusy = value;

                if (PropertyChanged != null)
                {

                    PropertyChanged(this, new PropertyChangedEventArgs("IsBusy"));
                    slcTile.Visibility = Visibility.Visible;
                }
            }
        }

        private List<DataItem> _dataItems = null;
        ESRI.ArcGIS.Client.Geometry.MapPoint _clickPoint;
        LocalMapService _mapService;

      


    private void QueryPoint_MouseClick(object sender, ESRI.ArcGIS.Client.Map.MouseEventArgs e)
        {
            _clickPoint = e.MapPoint;

            ESRI.ArcGIS.Client.Tasks.IdentifyParameters identifyParams = new IdentifyParameters()
            {
                Geometry = _clickPoint,
                MapExtent = MyMap.Extent,
                Width = (int)MyMap.ActualWidth,
                Height = (int)MyMap.ActualHeight,
                LayerOption = LayerOption.visible
            };

            IdentifyTask identifyTask = new IdentifyTask();
            identifyTask.Url = _mapService.UrlMapService;

            identifyTask.ExecuteCompleted += IdentifyTask_ExecuteCompleted;
            identifyTask.Failed += IdentifyTask_Failed;

            identifyTask.ExecuteAsync(identifyParams);

            GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
            graphicsLayer.Graphics.Clear();

            ESRI.ArcGIS.Client.Graphic graphic = new ESRI.ArcGIS.Client.Graphic()
            {
                Geometry = _clickPoint,
                Symbol = LayoutRoot.Resources["DefaultPictureSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol
            };
            graphicsLayer.Graphics.Add(graphic);
        }
    private string getMeaning(string s)
    {        
        switch (s.Trim().ToLower()) 
        {                
            case "khu_vuc": return "Khu vực";                
            case "tinh": return "Tỉnh";
            case "dien_tich": return "Diện tích";
            case "donvi_hc": return "Đơn vị hành chính";
            case "dan_so": return "Dân số";
            default: return s;            
        }
    }
        public void ShowFeatures(List<IdentifyResult> results)
        {
            _dataItems = new List<DataItem>();

            if (results != null && results.Count > 0)            {
                
                foreach (IdentifyResult result in results)
                {
                    Graphic feature = result.Feature;
                    IDictionary<string, object> idi = new Dictionary<string, object>();

                    string title = result.Value.ToString() + " (" + result.Feature.Attributes.Values.ElementAt(3) + ")";
                    for (int i = 2; i < feature.Attributes.Keys.Count; i++)
                    {
                        idi.Add((string)getMeaning(feature.Attributes.Keys.ElementAt(i)), (object)feature.Attributes.Values.ElementAt(i));  

                    }
                   // MessageBox.Show(idi.Values.ElementAt(3).ToString());
                    ds = Convert.ToInt64(idi.Values.ElementAt(3));
                    dt = Convert.ToDouble(idi.Values.ElementAt(4));
                    ten = string.Copy(idi.Values.ElementAt(1).ToString()); 

                    _dataItems.Add(new DataItem()
                    {
                        Title = title,
                        Data = idi
                    });                  
                }

                IdentifyDetailsDataGrid.ItemsSource = _dataItems[0].Data;

            }
        }

  

        private void IdentifyTask_ExecuteCompleted(object sender, IdentifyEventArgs args)
        {
            IdentifyDetailsDataGrid.ItemsSource = null;

            if (args.IdentifyResults != null && args.IdentifyResults.Count > 0)
            {
                IdentifyResultsPanel.Visibility = Visibility.Visible;

                ShowFeatures(args.IdentifyResults);
            }
            else
            {     
                IdentifyResultsPanel.Visibility = Visibility.Collapsed;
            }
        }

        public class DataItem
        {
            public string Title { get; set; }
            public IDictionary<string, object> Data { get; set; }
        }

        void IdentifyTask_Failed(object sender, TaskFailedEventArgs e)
        {
            MessageBox.Show("Identify failed. Error: " + e.Error);
        }

        private void mniCopy_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Windows.Media.Imaging.RenderTargetBitmap renderTargetBitmap =
                    new System.Windows.Media.Imaging.RenderTargetBitmap((int)MyMap.ActualWidth, (int)MyMap.ActualHeight, 96, 96, System.Windows.Media.PixelFormats.Pbgra32);
                renderTargetBitmap.Render(MyMap);
                Clipboard.SetImage(renderTargetBitmap);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Information);
            }

        }

        private void mniIn_Click(object sender, RoutedEventArgs e)
        {
            MainWindow.cntrlIn = true;           
            
        }
        private void khoitaoTK()
        {
            strTenBD = new string[64];
            strDT = new double[64];
            strDS = new Int64[64];
            slTK = 0;
            gridTK.Visibility = Visibility.Hidden;
            gridTimTinh.Visibility = Visibility.Hidden;
        }

        private void btnthemTK_Click(object sender, RoutedEventArgs e)
        {
            bool kt = true;
            for (int i = 0; i < slTK; i++)
                if (strTenBD[i].CompareTo(ten) == 0) kt = false;

            if (kt)
            {
                strDT[slTK] = dt;
                strDS[slTK] = ds;
                strTenBD[slTK] = ten;
                slTK++;
            }
                
        }

        private void btnThongke_Click(object sender, RoutedEventArgs e)
        {            

            List<TKDS> tkList = new List<TKDS>();

            for (int i = 0; i < slTK; i++)
            {
                tkList.Add(new TKDS()
                {
                    name = string.Copy(strTenBD[i]),
                    dt = strDT[i],
                    ds = strDS[i]
                });
            }

            //bsbDS.DisplayName = tkdsDisplay;
            chrTKDS.DataSource = tkList;
            chrTKDT.DataSource = tkList;
           
            cboTK.SelectedIndex = 0;
            hienTK(0);
        }

        private void hienTK(int index)
        {
            gridTK.Visibility = Visibility.Visible;

            if (index == 0)
            {
                chrTKDS.Visibility = Visibility.Visible;
                chrTKDT.Visibility = Visibility.Hidden;            
            }
            if (index == 1)
            {
                chrTKDS.Visibility = Visibility.Hidden;
                chrTKDT.Visibility = Visibility.Visible;              
            }          
        }

        private void cboTK_DropDownClosed(object sender, EventArgs e)
        {
            if (cboTK.SelectedIndex != -1) hienTK(cboTK.SelectedIndex);
        }

        private void btnTV_Click(object sender, RoutedEventArgs e)
        {
            gridTK.Visibility = Visibility.Hidden;
            khoitaoTK();
        }

        private void txtFind_MouseEnter(object sender, MouseEventArgs e)
        {
            txtFind.Opacity = 1;
        }

        private void txtFind_MouseLeave(object sender, MouseEventArgs e)
        {
            txtFind.Opacity = 0.5;
        }

     

        private void gridTimTinh_MouseEnter(object sender, MouseEventArgs e)
        {
            gridTimTinh.Opacity = 1;
        }

        private void gridTimTinh_MouseLeave(object sender, MouseEventArgs e)
        {
            gridTimTinh.Opacity = 0.7;
        }

        private void gridTimTinh_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataGrid dataGrid = sender as DataGrid;
            int selectedIndex = dataGrid.SelectedIndex;
            if (selectedIndex > -1)
            {
                FindResult findResult = (FindResult)gridTimTinh.SelectedItem;

                Graphic graphic = findResult.Feature;
                graphic.Symbol = LayoutRoot.Resources["DefaultFillSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol;
                GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
                graphicsLayer.Graphics.Clear();
                graphicsLayer.Graphics.Add(graphic);
            }
        }

        private void btnTimkiem_Click(object sender, RoutedEventArgs e)
        {
            if (txtFind.Text.Trim().CompareTo("") != 0 )
            {
                GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
                graphicsLayer.Graphics.Clear();

                FindTask findTask = new FindTask();
                findTask.Url = _mapService.UrlMapService;           
          
                FindParameters findParameters = new FindParameters();
                findParameters.LayerIds.AddRange(new int[] { 0 });
                findParameters.SearchFields.AddRange(new string[] { "Tinh" });

                Binding resultFeaturesBinding = new Binding("LastResult");

                resultFeaturesBinding.Source = findTask;

                gridTimTinh.SetBinding(DataGrid.ItemsSourceProperty, resultFeaturesBinding);

                findParameters.SearchText = txtFind.Text;
                findTask.ExecuteAsync(findParameters);
                gridTimTinh.Visibility = Visibility.Visible;
            }
                
        }

        private void txtFind_TextChanged(object sender, TextChangedEventArgs e)
        {
            gridTimTinh.Visibility = Visibility.Hidden;
        }
    
}

    public class TKDS
    {
        public string name { get; set; }
        public double dt { get; set; }
        public Int64 ds { get; set; }

    }
    


}
